﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;

public partial class User_Login : System.Web.UI.Page
{
    Cstudy.Tools.RegexTools regextools = new Cstudy.Tools.RegexTools();

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected bool CanLogin()
    {
        bool can = true;
        if(!(new Cstudy.BLL.Users().ExistUserName(NameBox.Text)))
        {
            can=false;
        }
        if(CodeBox.Text!=GetCode())
        {
            can=false;
        }
        return can;
    }

    protected void NameBox_TextChanged(object sender, EventArgs e)
    {
        string name = NameBox.Text.Trim();
        if (name.Length < 4)
        {
            vname.Text = "用户名至少4位";
            return;
        }
        if (new Cstudy.BLL.Users().ExistUserName(name))
        {
            vname.Text = "用户名正确";
        }
        else
        {
            vname.Text = "用户名不存在";
        }
    }

    protected void PwdBox_TextChanged(object sender, EventArgs e)
    {
        if (regextools.IsValidByte(PwdBox.Text, 5, 15))
        {
            pwdlit.Text = "";
        }
        else
        {
            pwdlit.Text = "密码必须是6到15位且非特殊字符";
        }
    }

    protected void TextBox1_TextChanged(object sender, EventArgs e)
    {
        if (CodeBox.Text == GetCode())
        {
            validatelit.Text = "验证码正确";
        }
        else
        {
            validatelit.Text = "验证码不正确";
        }
    }

    protected string GetCode()
    {
        return Session["AuthenticationCode"].ToString();
    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        Response.Redirect("Register.aspx");
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        if (CanLogin())
        {
            string pwd = new Cstudy.Tools.Tools().MakeMD5(PwdBox.Text);
            DataSet ds = new DataSet();
            ds = new Cstudy.BLL.Users().SelectUserByName(NameBox.Text);
            DataRow dr = ds.Tables[0].Rows[0];
            if (pwd == ds.Tables[0].Rows[0]["Password"].ToString())
            {
                ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "failalert", "alert('登录成功！');window.location.href='../';", true);
                HttpCookie cookie = new HttpCookie("user");
                cookie.Values["name"] = dr["UserName"].ToString();
                cookie.Values["userid"] = dr["UserID"].ToString();
                cookie.Expires = DateTime.Now.AddDays(7);
                Response.Cookies.Add(cookie);
                return;
            }
            ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "failalert", "alert('登录失败！密码不正确！');", true);
        }
    }
}